package com.common.base.utils

import android.util.Base64
import java.security.Key
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec

//DES ECB加解密
object DesEcbUtil {
    private const val ALGORITHM_DES = "DES/ECB/PKCS5Padding"
    private const val secretKey = "&*!Oj_3X"

    @Throws(Exception::class)
    fun encode(key: String, data: String): String {
        return encode(key, data.toByteArray())
    }

    @Throws(Exception::class)
    fun encode(key: String, data: ByteArray?): String {
        return try {
            val dks = DESKeySpec(key.toByteArray())
            val keyFactory = SecretKeyFactory.getInstance("DES")
            // key的长度不能够小于8位字节
            val secretKey: Key = keyFactory.generateSecret(dks)
            val cipher = Cipher.getInstance(ALGORITHM_DES)
            cipher.init(Cipher.ENCRYPT_MODE, secretKey)
            val bytes = cipher.doFinal(data)
            Base64.encodeToString(bytes, 3)
        } catch (e: Exception) {
            throw Exception(e)
        }
    }

    @Throws(Exception::class)
    fun decode(key: String, data: ByteArray?): ByteArray {
        return try {
            val dks = DESKeySpec(key.toByteArray())
            val keyFactory = SecretKeyFactory.getInstance("DES")
            // key的长度不能够小于8位字节
            val secretKey: Key = keyFactory.generateSecret(dks)
            val cipher = Cipher.getInstance(ALGORITHM_DES)
            cipher.init(Cipher.DECRYPT_MODE, secretKey)
            cipher.doFinal(data)
        } catch (e: Exception) {
            throw Exception(e)
        }
    }

    fun decodeValue(key: String = secretKey, data: String?): String? {
        return try {
            String(decode(key, Base64.decode(data, 3)))
        } catch (e: Exception) {
            ""
        }
    }
}